package com.ghsc.ghxc.jsb.ui.live.fragment

import android.Manifest
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.alivc.auicommon.common.base.callback.Callbacks
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.InteractionError
import com.aliyun.aliinteraction.uikit.uibase.util.LastLiveSp
import com.aliyun.auiappserver.AppServerApi
import com.aliyun.auiappserver.AppServerTokenManager
import com.aliyun.auiappserver.model.ListLiveRequest
import com.aliyun.auiappserver.model.LiveModel
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.config.AliLiveMediaStreamOptions
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.config.AppConfig
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.FragmentLiveListBinding
import com.ghsc.ghxc.jsb.ui.live.adapter.LiveListAdapter
import com.ghsc.ghxc.jsb.ui.live.view.CustLiveProtoType
import com.ghsc.ghxc.jsb.ui.live.view.LiveBlackList
import com.ghsc.ghxc.jsb.view.NotDataView
import com.google.gson.Gson
import com.permissionx.guolindev.PermissionX
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.fragment
 * 类名：LiveFragment
 * 创建时间：2024/5/10 11:02
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 直播
 */
class LiveFragment   : BaseVMFragment<LiveListVIewModel, FragmentLiveListBinding>(R.layout.fragment_live_list){



    var index:Int=0
    companion object {
        fun getInstance(index:Int): LiveFragment? {
            var fragment= LiveFragment()
            fragment.index=index
            return fragment
        }
    }

    override fun attachVMClass(): Class<LiveListVIewModel>? {
        return LiveListVIewModel::class.java
    }

    override fun lazyLoad() {
        loge("lazyLoad--直播直播直播直播直播直播--lazyLoad")

    }

    var userId: String by Preference(HttpConstant.USER_ID, "")
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if(isVisibleToUser ){
            if ( !TextUtils.isEmpty(AppServerTokenManager.getAppServerToken()) && !TextUtils.isEmpty(
                    Const.getUserId()) &&
                Const.getUserId() == userId) {
                //todo 调用列表的接口
            } else {
                showLoading()
                // 直播请求自己的接口 登录 login 参数 request
                AppServerTokenManager.login(userId, userId,
                    object : InteractionCallback<Void?> {
                        override fun onSuccess(data: Void?) {
                            loge("直播登录=")
                            dismissLoading()
                            Const.setUserId(userId)
                            if (!TextUtils.isEmpty(Const.getUserId())){
                                //todo 调用列表的接口
                                pageNo = 1
                                getListData()
                            }

                        }
                        override fun onError(interactionError: InteractionError?) {
                            dismissLoading()
                            showToast("服务器出错...")
                        }
                    })
            }

        }
    }




    //屏幕的宽度
    var widthPixels= AppConfig.getApplication().resources.displayMetrics.widthPixels
    //屏幕的密度
    var density= AppConfig.getApplication().resources.displayMetrics.density






    private val mAdapter: LiveListAdapter by lazy { LiveListAdapter((widthPixels/density)) }
    var mList = arrayListOf<LiveModel>()
    private var notDataView: View? = null
    var itemPosition :Int =-1
    override fun onResume() {
        super.onResume()
        if ( !TextUtils.isEmpty(AppServerTokenManager.getAppServerToken()) && !TextUtils.isEmpty(Const.getUserId()) &&
            Const.getUserId() == userId) {
            //todo 调用列表的接口
            pageNo = 1
            getListData()
        }else{
            showLoading()
            // 直播请求自己的接口 登录 login 参数 request
            AppServerTokenManager.login(userId, userId,
                object : InteractionCallback<Void?> {
                    override fun onSuccess(data: Void?) {
                        loge("直播登录=")
                        dismissLoading()
                        Const.setUserId(userId)
                        if (!TextUtils.isEmpty(Const.getUserId())){
                            //todo 调用列表的接口
                            pageNo = 1
                            getListData()
                        }

                    }
                    override fun onError(interactionError: InteractionError?) {
                        dismissLoading()
                        showToast("服务器出错...")
                    }
                })
        }
    }
    override fun initView(savedInstanceState: Bundle?) {

        notDataView = NotDataView.notDataView(requireActivity(), binding.rvList,binding.refreshLayout,"暂无数据")
        binding.rvList.layoutManager = GridLayoutManager(requireActivity(), 2)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        mAdapter.setEmptyView(notDataView!!)

        mAdapter.setOnFastClickListener { data, position ->
            PermissionX.init(this)
                .permissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request { allGranted, _, _ ->
                    loge("获取到权限了吗=" + allGranted+"ID="+mAdapter.getItem(position).id+"anchorId="+mAdapter.getItem(position).anchorId)
                    showLoading()
                    itemPosition=position
                    gotoLivePage(mAdapter.getItem(position).id, mAdapter.getItem(position).anchorId)


                }
        }
        initRefreshLayout()

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustSignKey.LIVE_START && rxBusBean.sign == CustSignKey.LIVE_START -> {
                        showToast("该直播已结束...")
                        dismissLoading()
                        binding.refreshLayout.autoRefresh()
                    }
                    rxBusBean.id == CustSignKey.LIVE_START_RUN && rxBusBean.sign == CustSignKey.LIVE_START_RUN -> {
                        dismissLoading()
                    }

                }
            }



    }
    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }

            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }
    private fun getListData() {
        var confBean =UserManager.getConfig()
        confBean?.let {
            var sysConfigResultData = it.getSysConfigBean(CustKey.configK57 )
            if(sysConfigResultData!=null){
                if(!TextUtils.isEmpty(sysConfigResultData.cfg_value)){
                    loge("哈哈==="+sysConfigResultData.cfg_value+" 接口里="+LiveBlackList.numberMultiple)
                    var nunm = sysConfigResultData.cfg_value.toInt()
                    mAdapter.setAddNumCount(if(LiveBlackList.numberMultiple>0) LiveBlackList.numberMultiple else nunm)
                }
            }
        }
        val request = ListLiveRequest()
        request.userId = Const.getUserId()
        request.pageNum = pageNo
        request.pageSize = 30

        loge("参数="+request.toString())

        AppServerApi.instance().getLiveList(request).invoke(object :
            InteractionCallback<List<LiveModel>> {
            override fun onSuccess(data: List<LiveModel>) {
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (data.isNotEmpty()){
                        mAdapter.replaceData(data)
//                        var list = arrayListOf<String>()
//                        list.clear()
//                        for (i in mAdapter.data.indices)
//                            list.add(mAdapter.data[i].anchorId)
//
//                        if (list.size>0){
//                            val map: HashMap<String, Any> = HashMap()
//                            map["uids"] = Gson().toJson(list)
//                            loge("商品列表参数：$map")
//                            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onGetLiveMultipleMethod(it1) }
//                        }
//                        if(mAdapter.data.size>0){
//                            RxBus.getDefault().post(
//                                RxBusBean(
//                                    CustSignKey.LIVE_LIST_DATA,
//                                    CustSignKey.LIVE_LIST_DATA,1,data
//                                )
//                            )
//                        }
                    } else {
                        mList.clear()
                        mAdapter.replaceData(mList)
                        mAdapter.setEmptyView(notDataView!!)
                    }
                } else {
                    mAdapter.addData(data)
//                    if(mAdapter.data.size>0){
//                        RxBus.getDefault().post(
//                            RxBusBean(
//                                CustSignKey.LIVE_LIST_DATA,
//                                CustSignKey.LIVE_LIST_DATA,2,data
//                            )
//                        )
//                    }
                }
            }



            override fun onError(interactionError: InteractionError?) {
                loge("出错了"+interactionError!!.msg+"e"+interactionError.toString())
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                mAdapter.setEmptyView(notDataView!!)
            }
        })



    }


    /**
     * 跳转直播页面
     *
     * @param liveId   直播Id
     * @param anchorId 主播Id
     */
    private fun gotoLivePage(liveId: String?, anchorId: String) {
        val param = CustLiveProtoType.OpenLiveParam()
        param.liveId = liveId
        param.nick = UserManager.getUserName()
        param.userAvatar = UserManager.getUserHead()
        val callback = Callbacks.Lambda<String> { success, data, errorMsg ->
            if (success) {
                // 成功后, 记录该场直播, 便于下次快速进入
                val lastLiveSp = LastLiveSp.INSTANCE
                lastLiveSp.lastLiveId = liveId ?: data
                lastLiveSp.lastLiveAnchorId = anchorId
            } else {
                showToast(errorMsg)
            }
        }
        val isAnchor = TextUtils.equals(Const.getUserId(), anchorId)
        if (isAnchor) {
            // 主播端: 开启直播
            param.role = LiveRole.ANCHOR

            // 推流支持动态配置
            val pusherOptions = AliLiveMediaStreamOptions()
            param.mediaPusherOptions = pusherOptions
        } else {
            // 观众端: 观看直播
            param.role = LiveRole.AUDIENCE
        }

        if (isAnchor) {
//            LivePrototype.getInstancece().setup(requireActivity(), param, callback)
            CustLiveProtoType.instance!!.setup(requireActivity(), param, callback)
        } else {
//            LivePrototype.getInstance().setup(requireActivity(), param, callback)
            CustLiveProtoType.instance!!.setup(requireActivity(), param, callback)
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LiveFragment) {
                showToast(it)
            }
            againLoginMsg.observe(this@LiveFragment) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
        }
    }
}